//
//  Register_Personal_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 05-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Register_Personal_ViewController.h"
#import "Register_Home_ViewController.h"
#import "dao.h"
#import "Flurry.h"

@interface Register_Personal_ViewController ()

@end

@implementation Register_Personal_ViewController

@synthesize textNames, textLastName, textRut, textNumber, textDay, textMonth;
@synthesize textYear, pickerView, textStreet, textNumberStreet, textReference, viewPicker, btnComuna;
@synthesize textEmail;
@synthesize dataArray, dataArrayId, backBarButtonItem, segmentedSexOption, segmentedFormaPago;
@synthesize json;
@synthesize jsonDireccionCliente;
@synthesize registerLogon;

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 180;

bool blnNumerActive = NO;
bool blnKeyboardClassicActive = NO;

NSString *strIdComuna = @"";
NSString *strNameComuna = @"";

UIActivityIndicatorView *aiViewBtnFormiPhone;

int intIdClienteiPhone = 0;
int intIdDireccionClienteiPhone = 0;

// Number of components.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// Total rows in our component.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [dataArray count];
}

// Display each row's data.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [dataArray objectAtIndex: row];
}

// Do something with the selected row.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    strIdComuna = [dataArrayId objectAtIndex: row];
    strNameComuna = [dataArray objectAtIndex: row];
    
    NSLog(@"strIdComuna   = %@", strIdComuna);
    NSLog(@"strNameComuna = %@", strNameComuna);
    
    [btnComuna setTag:[strIdComuna integerValue]];
    [btnComuna setTitle:strNameComuna forState:UIControlStateNormal];
    
}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}

/*
 
- (void) retrieveComunas{
    
    [dataArray removeAllObjects];
    [dataArrayId removeAllObjects];
    
    dataArray = [[NSMutableArray alloc] init];
    dataArrayId = [[NSMutableArray alloc] init];
    
    //{"idF":"1","Fd":"Intelectual""}
    
    for (int i = 0; i<22; i++)
    {
        NSString * strIdComuna = [NSString stringWithFormat:@"%i", i];
        NSString * strDescriptionComuna = [NSString stringWithFormat:@"Comuna_%i", i];
        
        [dataArrayId addObject:strIdComuna];
        [dataArray addObject:strDescriptionComuna];
    }
    
    [self.pickerView reloadComponent:0];
}

*/

- (void) retrieveComunas{
    
    [dataArray removeAllObjects];
    [dataArrayId removeAllObjects];
    
    dataArray = [[NSMutableArray alloc] init];
    dataArrayId = [[NSMutableArray alloc] init];
    
    //{"idF":"1","Fd":"Intelectual""}
    
    dao *objDAO = [[dao alloc] init];
    
    NSMutableArray *ArrayComunas;
    NSArray *ArrayComuna;
    
    ArrayComunas = [objDAO obtainComunas:4]; //Santiago
    
    for (int i = 0; i<ArrayComunas.count; i++)
    {
        ArrayComuna = ArrayComunas[i];
/*
         strIdComuna 			= [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
         strDescripcionComuna 	= [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
         strIdCiudad 			= [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
*/

        NSString * strIdComuna = ArrayComuna[0];
        NSString * strDescriptionComuna = ArrayComuna[1];
        
        [dataArrayId addObject:strIdComuna];
        [dataArray addObject:strDescriptionComuna];
    }
    
    [self.pickerView reloadComponent:0];
    
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event{

    
    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }
    
//------------------------------------------------------------------------
/*
    if (blnNumerActive) {
        
        CGRect viewFrame = self.view.frame;
        viewFrame.origin.y += PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
        
        [self.view setFrame:viewFrame];
        
        [UIView commitAnimations];
    }
*/
//-------------------------------------------------------------------------

    [self.view endEditing:YES];
    
    [super touchesBegan:touches withEvent:event ];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == textNames) {
        
        [textNames resignFirstResponder];
        [textLastName becomeFirstResponder];
        
    }else if (textField == textLastName) {
        
        [textLastName resignFirstResponder];
        [textRut becomeFirstResponder];
        
    }else if (textField == textRut) {

        [textRut resignFirstResponder];
        [textNumber becomeFirstResponder]; //Nuevo

    }else if (textField == textStreet) {

        if (blnKeyboardClassicActive) {
            [self hideKeyboard];
            blnKeyboardClassicActive = NO;
        }

        if (blnNumerActive) {
            [self hideKeyboard];
            blnNumerActive = NO;
        }
        
        [textStreet resignFirstResponder];
        [textNumberStreet becomeFirstResponder];

    }else if (textField == textReference) {
        
        if (blnKeyboardClassicActive) {
            [self hideKeyboard];
            blnKeyboardClassicActive = NO;
        }
        
        if (blnNumerActive) {
            [self hideKeyboard];
            blnNumerActive = NO;
        }

        [textReference resignFirstResponder];
        
    }else{
        [self.view endEditing:YES];
    }
/*
 
 CGRect viewFrame = self.view.frame;
 viewFrame.origin.y += PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
 
 [UIView beginAnimations:nil context:NULL];
 [UIView setAnimationBeginsFromCurrentState:YES];
 [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
 
 [self.view setFrame:viewFrame];
 
 [UIView commitAnimations];
*/
    return NO;
}

- (NSString *) obtenerRutaBD{
    NSString *dirDocs;
    NSArray *rutas;
    NSString *rutaBD;
    
    rutas = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    dirDocs = [rutas objectAtIndex:0];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    rutaBD = [[NSString alloc] initWithString:[dirDocs stringByAppendingPathComponent:@"ecommerce.sqlite"]];
    
    if([fileMgr fileExistsAtPath:rutaBD] == NO){
        [fileMgr copyItemAtPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ecommerce.sqlite"] toPath:rutaBD error:NULL];
    }
    
    return rutaBD;
}

- (void) retrieveClient{
    
    dao *objDAO = [[dao alloc] init];
    int intIdUser;
    
    intIdUser = [objDAO obtainCurrentIdUser];
    
    //Obtiene los datos almacenados desde sql Lite
    //------------------------------------------------
    NSString *ubicacionDB = [self obtenerRutaBD];
    
    if(!(sqlite3_open([ubicacionDB UTF8String], &bd) == SQLITE_OK)){
        NSLog(@"Database connection failure irn");
    }
    
    NSString *sqlSelect = [NSString stringWithFormat:@"SELECT MC_RUT_CLIENTE, MC_DIGITO, MC_NOMBRE_COMPLETO, MC_APELLIDOS, MC_TELEFONO, MC_DIA, MC_MES, MC_ANO, MC_SEXO, MCLI_FORMA_PAGO, MC_EMAIL FROM ECOM_MAESTRO_CLIENTES WHERE USIS_ID = %i", intIdUser];
    
    const char *sentenciaSQL = [sqlSelect UTF8String];
    
    sqlite3_stmt *sqlStatement;
    
    if(sqlite3_prepare_v2(bd, sentenciaSQL, -1, &sqlStatement, NULL) != SQLITE_OK){
        NSLog(@"Exception to prepare statement");
    }
    
    NSString *strRutCliente, *strIdComuna, *strDigito, *strNombreCompleto, *strApellidos, *strTelefono, *strDia, *strMes, *strAno, *strSexo, *strFormaPago, *strEmail;
    
    while(sqlite3_step(sqlStatement) == SQLITE_ROW){
        
        strRutCliente = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
        
        strDigito = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
        
        strNombreCompleto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
        
        strApellidos = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
        
        strTelefono = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
        
        strDia = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
        
        strMes = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
        
        strAno = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,7 )];
        
        strSexo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,8 )];
        
        strFormaPago = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,9 )];

        strEmail = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,10 )];
    }
    
    NSLog(@"strRutCliente     =%@", strRutCliente);
    NSLog(@"strIdComuna       =%@", strIdComuna);
    NSLog(@"strDigito         =%@", strDigito);
    
    NSLog(@"strNombreCompleto =%@", strNombreCompleto);
    NSLog(@"strApellidos      =%@", strApellidos);
    NSLog(@"strTelefono       =%@", strTelefono);
    
    NSLog(@"strDia =%@", strDia);
    NSLog(@"strMes =%@", strMes);
    NSLog(@"strAno =%@", strAno);
    
    NSLog(@"strSexo=%@", strSexo);
    NSLog(@"strFormaPago=%@", strFormaPago);
    NSLog(@"strEmail=%@", strEmail);
    
    textNames.text = [strNombreCompleto stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];;
    textLastName.text = [strApellidos stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];;
    textNumber.text = strTelefono;
    textEmail.text = strEmail;
    
    if ( ([strRutCliente  isEqual: @"0"]) || (strRutCliente == NULL) )  {

        strRutCliente = @"";
        strDigito = @"";

    }else {
        textRut.text = [NSString stringWithFormat:@"%@-%@", strRutCliente, strDigito];
        
    }

    textDay.text = strDia;
    textMonth.text = strMes;
    textYear.text = strAno;
    
    if ([strSexo  isEqual: @"male"]) {

        self.segmentedSexOption.selectedSegmentIndex = 0;
        
    }else{
        self.segmentedSexOption.selectedSegmentIndex = 1;
    }
    
    [self retrieveClientDirection];
    
}

-(void) retrieveClientDirection{

    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = 0;
    NSArray *ArrayDireccion;

    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    ArrayDireccion = [objDAO obtainDireccionCliente:intIdUsuario];
    
    if (ArrayDireccion.count > 0) {

        [btnComuna setTag:[ArrayDireccion[5] intValue]]; //IdComuna para grabar en la tabla de dirección
        [btnComuna setTitle:ArrayDireccion[6] forState:UIControlStateNormal];
        [btnComuna setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        textStreet.text = ArrayDireccion[1];
        textNumberStreet.text = ArrayDireccion[2];
        textReference.text = ArrayDireccion[3];
        
        intIdDireccionClienteiPhone = [ ArrayDireccion[7] intValue];
    }
}

//****************************************************************************************************
//Observación, se actualiza la data desde el CLoud del cliente como de su dirección en SqlLite
- (bool) clientInfoCloud:(int) intIdUsuario {
    
    dao *objDAO = [[dao alloc] init];
    
    bool blnRetorno = YES;
    int intRetorno = 0;
    int intRutCliente = 0;
    int intDia = 0;
    int intMes = 0;
    int intAno = 0;
    int intFormaPago = 1;
    
    NSString *strDigito = @"";
    NSString *strNombreCompleto = @"";
    NSString *strApellidos = @"";
    NSString *strTelefono = @"";
    NSString *strSex = @"";
    NSString *strFechaNacimiento = @"";
    NSString *strEmail = @"";
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonDatosCliente&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        //[{"idcli":"28", "tpcli":"1", "rut":"12814052", "dig":"2", "nom":"Yessica Andrea", "ape":"Arias Sudy", "rz":"", "nomf":"", "tel":"", "fnan":"19752323", "sex":"F", "rub":"", "cel":"56276800", "mail":"yessica.arias.sudy@gmail.com" }]
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        intIdClienteiPhone = [ [[json objectAtIndex:0] objectForKey:@"idcli"] intValue];
        intRutCliente = [ [[json objectAtIndex:0] objectForKey:@"rut"] intValue];
        strDigito = [[json objectAtIndex:0] objectForKey:@"dig"];
        strDigito = [[json objectAtIndex:0] objectForKey:@"dig"];
        strNombreCompleto = [[json objectAtIndex:0] objectForKey:@"nom"];
        strApellidos = [[json objectAtIndex:0] objectForKey:@"ape"];
        strTelefono = [[json objectAtIndex:0] objectForKey:@"cel"];
        strFechaNacimiento = [[json objectAtIndex:0] objectForKey:@"fnan"];
        strEmail = [[json objectAtIndex:0] objectForKey:@"email"];
        
        if (  (![strFechaNacimiento  isEqual: @"0"]) && (![strFechaNacimiento  isEqual: @""])  ) {
            
            intDia = [[strFechaNacimiento substringWithRange:NSMakeRange(strFechaNacimiento.length-2, 2 )] intValue];
            intMes = [[strFechaNacimiento substringWithRange:NSMakeRange(strFechaNacimiento.length-4, 2 )] intValue];
            intAno = [[strFechaNacimiento substringWithRange:NSMakeRange(0, 4)] intValue];
            
        }else{
            intDia = 0;
            intMes = 0;
            intAno = 0;
        }
        
        strSex = [[json objectAtIndex:0] objectForKey:@"sex"];
        
        if ([objDAO obtainMaestroClientes: intIdUsuario] > 0) {
            //Actualizamos
            
            intRetorno = [objDAO upateMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
            
            if (intRetorno > 0) {
                
                blnRetorno = YES;
            } else {
                blnRetorno = NO;
            }
            
        }else{
            //Insertamos
            intRetorno = [objDAO insertMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
            
            if (intRetorno > 0) {
                
                blnRetorno = YES;
            } else {
                blnRetorno = NO;
            }
        }
        
        if (blnRetorno) {
            
            blnRetorno = [self clientDirectionInfoCloud:intIdUsuario intRutCliente:intRutCliente];
        }
        
    }else{
        blnRetorno = NO;
    }
    
    return blnRetorno;
}


- (bool) clientDirectionInfoCloud:(int) intIdUsuario intRutCliente:(int) intRutCliente{
    
    dao *objDAO = [[dao alloc] init];
    
    int intRetorno = 0;
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com//MobileJsonCliente.aspx?strJsonBase=JsonDireccionCliente&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        //[{"iddir":"46", "tdir":"1", "idcom":"3", "idcom":"Lampa", "idciu":"4", "idciu":"Santiago", "dir":"Centenario de San Miguel", "numd":"935", "desc":"", "ref":"Costado lider", "nom":"", "ape":"", "ctel":"", "tel":"" }]
        
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        [objDAO deleteDireccionCliente:intIdUsuario];
        
        intIdDireccionClienteiPhone = [ [[json objectAtIndex:0] objectForKey:@"iddir"] intValue];
        
        if (intIdDireccionClienteiPhone != 0) {
            
            int intIdComuna = [ [[json objectAtIndex:0] objectForKey:@"idcom"] intValue];
            
            NSString *strStreet = [[json objectAtIndex:0] objectForKey:@"dir"];
            
            NSString *strNumberStreet = [[json objectAtIndex:0] objectForKey:@"numd"];
            
            NSString *strReference = [[json objectAtIndex:0] objectForKey:@"ref"];
            
            intRetorno = [objDAO insertDireccionCliente:intIdUsuario intIdDireccion:intIdDireccionClienteiPhone intRutCliente:intRutCliente strDireccion:strStreet strNumero:strNumberStreet strReferencia:strReference intIdComuna: intIdComuna];
            
            if (intRetorno <= 0) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"Error al actualizar la dirección del cliente, intente nuevamente."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
                
                return NO;
                
            }else{
                
                return YES;
            }
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"Debe especificar su direción de despacho en el sistema."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return YES; //Por ahora si esta creado el usuario en el portal, pero no especificó dirección lo obligamos a completarla.
        }
        
    }else{
        return NO;
    }
}


- (void)viewWillAppear:(BOOL)animated {
    
    [self showTabBar];
//****************************************************************************************************
    intIdClienteiPhone = 0;               //--> Cliente de la tabla CLIENTE
    intIdDireccionClienteiPhone = -1;     //--> Con este Id en -1 se indica que es un insert de dirección
//****************************************************************************************************
    blnNumerActive = NO;
    blnKeyboardClassicActive = NO;
    viewPicker.hidden = YES;
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    //0 = Home App
    //1 = Register
    //2 = Edición del despacho
    
    if ([objDAO obtainRegisterBack] == 1) {
    //Si no viene del registro no hay retorno

        [self.backBarButtonItem setImage:[UIImage imageNamed:@"icono_atras_transparente.png"]]; //icono_llamar.png
    }

    NSString *strClienteAction = [objDAO obtainClientAction]; //Identifica si se deben cargar desde sQlLite los datos del cliente por si es un ingreso o actualización

    if ([strClienteAction  isEqual: @"Load"]) {

        //*******************************************************
        //Observación: Nueva lógica de negocio

        //5.- Logeado con correo, 1.- Logeado con Facebook
        int intUsrLoggedFacebook = [objDAO obtainUsrLogged:1 idUsuario:intIdUsuario];
        
        if (intUsrLoggedFacebook == -1) {         //Si no es un Login con Facebook

            int intIdUsuario = [objDAO obtainCurrentIdUser];
            bool blnRetorno = YES;
            
            blnRetorno = [self clientInfoCloud:intIdUsuario];
            
            if (blnRetorno) {
                
                [self retrieveClient];
                
            }else{
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"Error remoto al intentar obtener la información del cliente, intente nuevamente."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            
        }else{
            //Se asume que por ser un Login con facebook reciente, la información esta local en SqlLite
                [self retrieveClient];
        }
        
        //*******************************************************
        
        
//      [self retrieveClient];
    }
    
    
//  [self.view endEditing:YES];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    textNames.delegate = self;
    textLastName.delegate = self;
    textRut.delegate = self;
    textNumber.delegate = self;
    textDay.delegate = self;
    textMonth.delegate = self;
    
    textYear.delegate = self;
    textStreet.delegate = self;
    textNumberStreet.delegate = self;
    textReference.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)callNumber:(id)sender {

    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (IBAction)showPickerComuna:(id)sender {
    
    if (blnKeyboardClassicActive) {
        [self hideKeyboard];
        blnKeyboardClassicActive = NO;
        [self.view endEditing:YES];
    }
    
    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
        [self.view endEditing:YES];
    }
    
    [self retrieveComunas];
    
    // Init the picker view.
    pickerView = [[UIPickerView alloc] init];
    
    // Set the delegate and datasource. Don't expect picker view to work
    // correctly if you don't set it.
    [pickerView setDataSource: self];
    [pickerView setDelegate: self];
    
    pickerView.showsSelectionIndicator = YES;
    
    [pickerView selectRow:2 inComponent:0 animated:YES];
    
    viewPicker.hidden = NO;
}

-(void)cancelNumberPad{
    
    blnNumerActive = NO;
    
    [self hideKeyboard];
    
    [self.view endEditing:YES];
}

- (void)doneWithNumberPad:(id)sender {

   blnNumerActive = NO;
//-------------------------------------------------------------------------
//Observación: Bajamos el teclado

    [self hideKeyboard];
    [self.view endEditing:YES];
//-------------------------------------------------------------------------

}

- (IBAction)closeViewPicker:(id)sender {

    viewPicker.hidden = YES;

    [self.btnComuna setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [self.btnComuna setTitle:strNameComuna forState:UIControlStateNormal];
    
    [textStreet becomeFirstResponder];
    
}

-(void) hideKeyboard{

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
    
}

- (void) upKeyboardClasic{

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (void) upKeyboardNumber{

    blnNumerActive = YES;
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
    
}

- (IBAction)changePhoneNumber:(id)sender {

    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }
    
    if (!blnNumerActive) {
        blnNumerActive = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textNumber.inputAccessoryView = numberToolbar;
    }

}

- (IBAction)changeDay:(id)sender {
    
    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }

    if (!blnNumerActive) {

        blnNumerActive = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textDay.inputAccessoryView = numberToolbar;
    }
}

- (IBAction)changeMonth:(id)sender {
    
    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }

    if (!blnNumerActive) {

        blnNumerActive = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textMonth.inputAccessoryView = numberToolbar;
    }
}

- (IBAction)changeYear:(id)sender {

    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }
    
    if (!blnNumerActive) {

        blnNumerActive = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textYear.inputAccessoryView = numberToolbar;
    }
}

-(NSInteger)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
    // Manage Date Formation same for both dates
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [formatter dateFromString:date1];
    NSDate *endDate = [formatter dateFromString:date2];
    
    unsigned flags = NSDayCalendarUnit;
    NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
    
    NSInteger dayDiff = [difference year];
    
    return dayDiff;
}

-(NSInteger)howManyDaysHavePast:(NSDate*)lastDate today:(NSDate*)today {
	NSDate *startDate = lastDate;
	NSDate *endDate = today;
	NSCalendar *gregorian = [[NSCalendar alloc]
							 initWithCalendarIdentifier:NSGregorianCalendar];
	unsigned int unitFlags = NSDayCalendarUnit;
	NSDateComponents *components = [gregorian components:unitFlags
												fromDate:startDate
												  toDate:endDate options:0];
	NSInteger days = [components day];

	return days;
}

- (IBAction)endChangeYear:(id)sender {

//Si la fecha esta bien digitada y validada, calculo la edad de la persona y genero el log en Flurry
    if ((textDay.text.length > 0) && (textMonth.text.length > 0) && (textYear.text.length > 0)) {

        //Fecha actual
        NSDate *fechaActual = [NSDate date];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd-MM-yyyy"];
        
        NSString *strAgeDate = [NSString stringWithFormat:@"%@-%@-%@", textDay.text, textMonth.text, textYear.text];
        NSDate *dateFechaNacimiento = [dateFormat dateFromString:strAgeDate];

//--------
        
        NSDate *startDate = dateFechaNacimiento;
        NSDate *endDate = fechaActual;
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];
        unsigned int unitFlags = NSDayCalendarUnit;
        NSDateComponents *components = [gregorian components:unitFlags
                                                    fromDate:startDate
                                                      toDate:endDate options:0];
        NSInteger days = [components day];

        float userAge = roundf(days/365);
        
        int edad = (int)userAge;
        
        /*Flurry Stack trace Edad*/
        //--------------------------
        [Flurry setAge:edad];
        //--------------------------
        
        NSLog(@"edad = %i", edad);
    }
    
}

- (IBAction)changeSexOption:(id)sender {
    
    switch (self.segmentedSexOption.selectedSegmentIndex) {
        case 0:{
            /* Hombre */

            /*Flurry Stack trace*/
            //--------------------------
            [Flurry setGender:@"m"];
            //--------------------------
            
            break;
        }
        case 1:{
            /* Mujer */
            
            /*Flurry Stack trace*/
            //--------------------------
            [Flurry setGender:@"f"];
            //--------------------------
            
            break;
        }
    }
    
}

- (IBAction)changeStreetNumber:(id)sender {

    if (blnKeyboardClassicActive) {
        [self hideKeyboard];
        blnKeyboardClassicActive = NO;
    }
    
    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }
    
    if (!blnNumerActive) {

        blnNumerActive = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textNumberStreet.inputAccessoryView = numberToolbar;
    }
}

- (IBAction)changeStreet:(id)sender {

    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }
    
    blnKeyboardClassicActive = YES;
    [self upKeyboardClasic];
}

- (IBAction)changeReference:(id)sender {

    if (blnNumerActive) {
        [self hideKeyboard];
        blnNumerActive = NO;
    }
    
    blnKeyboardClassicActive = YES;
    [self upKeyboardClasic];
}

- (IBAction)backAction:(id)sender {

    dao *objDAO = [[dao alloc] init];
    
    if ([objDAO obtainRegisterBack] != 1) {

        UIViewController *rvController = [self.storyboard instantiateViewControllerWithIdentifier:@"Dispatch"];
        [self.navigationController popViewControllerAnimated:rvController];
    }
    
/*
 dao *objDAO = [[dao alloc] init];
 
 //0 = Home App
 //1 = Register
 //2 = Edición del despacho
 
 [objDAO deleteRegisterBack];
 [objDAO insertRegisterBack:1];
 
 [self performSegueWithIdentifier:@"segueRegisterData" sender:nil];

*/
    
}

//Cesar Manoli F. Lautaro Riquelme Hermanos
//Compras y recepciones de productos

- (IBAction)register:(id)sender {
    
}

-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
    return [StrText rangeOfString:StrSearchTerm
                          options:NSCaseInsensitiveSearch].location != NSNotFound;
}

-(bool) validarRut: (NSString *) strRut {
    
    int rut = 0;
    int Digito;
    int Contador;
    int Multiplo;
    int Acumulador;
    NSString *dvCalulado;
    
//-----------------------------------------------------------------------------------------
    strRut = [strRut stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
    strRut = [strRut stringByReplacingOccurrencesOfString: @ "-" withString: @ ""];
    
    int rutAux = [[strRut substringWithRange:NSMakeRange(0, strRut.length-1)] intValue];
//  char dv = (char) [strRut substringWithRange:NSMakeRange(strRut.length-1, 1 )];
    NSString *dv = [[strRut substringWithRange:NSMakeRange(strRut.length-1, 1 )] uppercaseString];
    
    rut = rutAux;
//-----------------------------------------------------------------------------------------
    
    Contador = 2;
    Acumulador = 0;
    
    while (rut != 0)
    {
        Multiplo = (rut % 10) * Contador;
        Acumulador = Acumulador + Multiplo;
        rut = rut/10;
        Contador = Contador + 1;
        if (Contador == 8)
        {
            Contador = 2;
        }
    }
    
    Digito = 11 - (Acumulador % 11);
    
    dvCalulado = [NSString stringWithFormat:@"%i", Digito];   //Digito.ToString().Trim();
    
    if (Digito == 10 )
    {
        dvCalulado = @"K";
    }
    if (Digito == 11)
    {
        dvCalulado = @"0";
    }

    NSLog(@"dv=%@", dv);
    
    NSLog(@"dvCalulado =%@", dvCalulado);
    
    if ([dvCalulado isEqualToString:dv]) {
        
        return YES;
        
    }else{
        return NO;
    }
    
}

-(bool) validarRegistro{

    bool blnRetorno = YES;
/*
    NSString *strMensaje = @"";

//Nombres
    if (textNames.text.length == 0) {
        [textNames becomeFirstResponder];
        strMensaje = @"Debe ingresar el nombre del cliente.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Apellidos
    if (textLastName.text.length == 0) {
        [textLastName becomeFirstResponder];
        strMensaje = @"Debe ingresar los apellidos del cliente.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//RUT
    
    if (textRut.text.length == 0) {
        [textRut becomeFirstResponder];
        strMensaje = @"Debe ingresar el rut del cliente.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    bool blnValidaRut = YES;

    textRut.text = [textRut.text uppercaseString];
    
    NSLog(@"textRut.text =%@", textRut.text);
    
    blnValidaRut = [self validarRut:textRut.text];
    
    if (!blnValidaRut) {
        [textRut becomeFirstResponder];
        strMensaje = @"El rut ingresado es incorrecto.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Número Celular
    if (textNumber.text.length == 0) {
        [textNumber becomeFirstResponder];
        strMensaje = @"Debe ingresar el número de celular.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }

    if (textNumber.text.length < 8) {
        [textNumber becomeFirstResponder];
        strMensaje = @"Debe ingresar un número válido de 8 caracteres.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Dia
    if (textDay.text.length == 0) {
        [textDay becomeFirstResponder];
        strMensaje = @"Debe ingresar el día de nacimiento.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }

//Mes
    if (textMonth.text.length == 0) {
        [textMonth becomeFirstResponder];
        strMensaje = @"Debe ingresar el mes de nacimiento.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Ano
    if (textYear.text.length == 0) {
        [textYear becomeFirstResponder];
        strMensaje = @"Debe ingresar el año de nacimiento.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//------------------------------
//Comuna
    NSString *strComuna = btnComuna.titleLabel.text;

    //Si es el valor por defecto lo borramos para validar
    if ([strComuna  isEqual: @"Comuna"]) {
        strComuna = @"";
    }
    
    if (strComuna.length == 0) {
        strMensaje = @"Debe seleccionar una comuna.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Calle
    if (textStreet.text.length == 0) {
        [textStreet becomeFirstResponder];
        strMensaje = @"Debe indicar una calle.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Número
    if (textNumberStreet.text.length == 0) {
        [textNumberStreet becomeFirstResponder];
        strMensaje = @"Debe indicar un número de calle.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Referencia
    if (textReference.text.length == 0) {
        [textReference becomeFirstResponder];
        strMensaje = @"Debe indicar una referencia.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
//Forma de pago
*/
        return blnRetorno;
}

-(BOOL) insertClientCloud:(int) intIdUsuario
                 strEmail:(NSString *) strEmail
         intIdTipoCliente:(int) intIdTipoCliente
            intRutCliente:(int) intRutCliente
                strDigito:(NSString *) strDigito
        strNombreCompleto:(NSString *) strNombreCompleto
             strApellidos:(NSString *) strApellidos
           strRazonSocial:(NSString *) strRazonSocial
        strNombreFantasia:(NSString *) strNombreFantasia
              strTelefono:(NSString *) strTelefono
               strCelular:(NSString *) strCelular
       intFechaNacimiento:(int) intFechaNacimiento
                  strSexo:(NSString *) strSexo
               intIdRubro:(int) intIdRubro
         strFlagDireccion:(NSString *) strFlagDireccion{

    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonRegistraClientes&strIdUsuario=%i&strEmail=%@&strIdTipoCliente=%i&strRutCliente=%i&strDigito=%@&strNombreCompleto=%@&strApellidos=%@&strRazonSocial=%@&strNombreFantasia=%@&strTelefono=%@&strCelular=%@&strFechaNacimiento=%i&strSexo=%@&strIdRubro=%i&strFlagDireccion=%@",
                        intIdUsuario, strEmail, intIdTipoCliente, intRutCliente, strDigito, strNombreCompleto, strApellidos, strRazonSocial, strNombreFantasia, strTelefono, strCelular, intFechaNacimiento, strSexo, intIdRubro, strFlagDireccion];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        NSLog(@"Exito");

        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        int intIdCliente = 0;
        
        intIdCliente = [ [[json objectAtIndex:0] objectForKey:@"usrid"] intValue];
        
        if (intIdCliente > 0) {
            intIdClienteiPhone = intIdCliente;
        }
        
        //****Id del cliente relacionado al usuario para grabar la sucursal por defecto con los datos de dirección
//      intIdClienteiPhone = [ [[json objectAtIndex:0] objectForKey:@"usrid"] intValue];
        
//      [aiViewBtnFormiPhone stopAnimating];

        return YES;
    }else{
        
        NSLog(@"Error");
        
//      [aiViewBtnFormiPhone stopAnimating];
        
        return NO;
    }
}

-(BOOL) insertClientDirectionCloud:(int) intIdUsuario
             intIdDireccionCliente:(int) intIdDireccionCliente
                intIdTipoDireccion:(int) intIdTipoDireccion
                       intIdComuna:(int) intIdComuna
                       intIdCiudad:(int) intIdCiudad
                      intIdCliente:(int) intIdCliente
                      strDireccion:(NSString *) strDireccion
               sstrNumeroDireccion:(NSString *) strNumeroDireccion
                    strDescripcion:(NSString *) strDescripcion
                     strReferencia:(NSString *) strReferencia
         strNombreCompletoContacto:(NSString *) strNombreCompletoContacto
               strApellidoContacto:(NSString *) strApellidoContacto
                    strCodTelefono:(NSString *) strCodTelefono
                       strTelefono:(NSString *) strTelefono {

    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonRegistraDireccion&strIdUsuario=%i&strIdTipoDireccion=%i&strIdComuna=%i&strIdCiudad=%i&strIdCliente=%i&strDireccion=%@&strNumeroDireccion=%@&strDescripcion=%@&strReferencia=%@&strNombreCompletoContacto=%@&strApellidoContacto=%@&strCodTelefono=%@&strTelefono=%@&strEstado=-1&strIdDirecccionClienteIN=%i",
                        intIdUsuario, intIdTipoDireccion, intIdComuna, intIdCiudad, intIdCliente, strDireccion, strNumeroDireccion, strDescripcion, strReferencia, strNombreCompletoContacto, strApellidoContacto, strCodTelefono, strTelefono, intIdDireccionCliente];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        NSLog(@"Exito");
        
        jsonDireccionCliente = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        intIdDireccionClienteiPhone = [ [[jsonDireccionCliente objectAtIndex:0] objectForKey:@"iddir"] intValue];;
        
        [aiViewBtnFormiPhone stopAnimating];
        
        return YES;
    }else{
        
        NSLog(@"Error");
        
        [aiViewBtnFormiPhone stopAnimating];
        
        return NO;
    }
}

-(bool) ingresarDireccionCliente:(int) intIdUsuario intRutCliente:(int) intRutCliente {

    dao *objDAO = [[dao alloc] init];

    
    bool blnRetorno = YES;
    bool blnReturnCloud = YES;
    int intRetorno = 0;
    
    int intIdComuna = (int) btnComuna.tag;
    
    NSString *strDireccion = [textStreet.text stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];
    NSString *strNumeroDireccion = [textNumberStreet.text stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];
    NSString *strReferencia = [textReference.text stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];

    //******OJO que este campo intIdDireccionCliente debe tener valor si viene de un recarga de formulario
    
    blnReturnCloud = [self insertClientDirectionCloud:intIdUsuario intIdDireccionCliente:intIdDireccionClienteiPhone intIdTipoDireccion:1 intIdComuna:intIdComuna intIdCiudad:4 intIdCliente:intIdClienteiPhone strDireccion:strDireccion sstrNumeroDireccion:strNumeroDireccion strDescripcion:@"" strReferencia:strReferencia strNombreCompletoContacto:@"" strApellidoContacto:@"" strCodTelefono:@"" strTelefono:@""];
    
    if (blnReturnCloud) { //Se grabó exitosamente la dirección
        
        [objDAO deleteDireccionCliente:intIdUsuario];
        
        intRetorno = [objDAO insertDireccionCliente:intIdUsuario intIdDireccion:intIdDireccionClienteiPhone intRutCliente:intRutCliente strDireccion:textStreet.text strNumero:textNumberStreet.text strReferencia:textReference.text intIdComuna: intIdComuna];
        
        if (intRetorno <= 0) {
            blnRetorno = NO;
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"Error al actualizar la dirección del cliente, intente nuevamente."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
        }else{
            blnRetorno = YES;
            
            [objDAO deleteClientAction];
            [objDAO insertClientAction:@"Load"]; //Indicamos que en la ventana de edición del cliente se debe hacer load desde SqlLite
        }
    }else{
        blnRetorno = NO;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Error remoto al ingresar la dirección del cliente, intente nuevamente."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }

    return blnRetorno;
}

-(bool) registerForm{

    bool blnRetorno = YES;

    if ([self validarRegistro] == YES) {
        dao *objDAO = [[dao alloc] init];
        int intIdUsuario = [objDAO obtainCurrentIdUser];
//      NSString *strEmail = [objDAO obtainEmailUserSistem:intIdUsuario];
        
        NSString *strRut = textRut.text;
        strRut = [strRut stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
        strRut = [strRut stringByReplacingOccurrencesOfString: @ "-" withString: @ ""];
        
        int intRutCliente = [[strRut substringWithRange:NSMakeRange(0, strRut.length-1)] intValue];
        NSString *strDigito = [[strRut substringWithRange:NSMakeRange(strRut.length-1, 1 )] uppercaseString];
        
        textRut.text = [textRut.text stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
        
        NSString *strNombreCompleto = textNames.text;
        NSString *strApellidos = textLastName.text;
        NSString *strTelefono = textNumber.text;
        int intDia = [textDay.text intValue];
        int intMes = [textMonth.text intValue];
        int intAno = [textYear.text intValue];
        
        NSString *strDay = textDay.text;
        NSString *strMonth = textMonth.text;
        NSString *strEmail = textEmail.text;
        
        if (strDay.length == 1) {
            strDay = [NSString stringWithFormat:@"0%@", strDay];
        }
        
        if (strMonth.length == 1) {
            strMonth = [NSString stringWithFormat:@"0%@", strMonth];
        }
        
        NSString *strFechaNacimiento = [NSString stringWithFormat:@"%@%@%@", textYear.text, strMonth, strDay];
        
        NSString *strSex = @"";
        int intFormaPago = 0;
        
        if (segmentedSexOption.selectedSegmentIndex == 0) {
            strSex = @"M"; //@"male";
        }else{
            strSex = @"F"; //@"female";
        }
        
        if (segmentedFormaPago.selectedSegmentIndex == 0) {
            intFormaPago = 0;
        }else{
            intFormaPago = 1;
        }
        
        int intRetorno = 0;
        
        strNombreCompleto = [strNombreCompleto stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];
        strApellidos = [strApellidos stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];
        
        bool blnReturnCloud = [self insertClientCloud:intIdUsuario strEmail:strEmail intIdTipoCliente:1 intRutCliente:intRutCliente strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strRazonSocial:@"" strNombreFantasia:@"" strTelefono:@"" strCelular:strTelefono intFechaNacimiento:[strFechaNacimiento intValue] strSexo:strSex intIdRubro:-1 strFlagDireccion:@""];
        
        if (blnReturnCloud) {
            
            NSLog(@"Exito");
            
            if ([objDAO obtainMaestroClientes: intIdUsuario] > 0) {
                //Actualizamos
                
                strNombreCompleto = [strNombreCompleto stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];
                strApellidos = [strApellidos stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];
                
                intRetorno = [objDAO upateMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
                
                if (intRetorno > 0) {
                    //Remota y localmente ingresamos la dirección
                    blnRetorno = [self ingresarDireccionCliente: intIdUsuario intRutCliente:intRutCliente];
                    
                }else{
                    blnRetorno = NO;
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:@"Error al actualizar los datos del cliente, intente nuevamente."
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
                
            }else{
                
                strNombreCompleto = [strNombreCompleto stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];
                strApellidos = [strApellidos stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];
                
                intRetorno = [objDAO insertMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
                
                if (intRetorno > 0) { //Creamos la dirección por estan en tablas separadas
                    
                    blnRetorno = [self ingresarDireccionCliente: intIdUsuario intRutCliente:intRutCliente];
                    
                }else{
                    blnRetorno = NO;
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:@"Error al grabar los datos del cliente, intente nuevamente."
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
                
            } //if ([objDAO obtainMaestroClientes: intIdUsuario] > 0)
            
            //Registramos que el usuario se registró en el sistema para las secuencias de nuevos login y compras
            if (blnRetorno) { //Todo bien lo damos por registrado
                [objDAO insertUsrRegistered:intIdUsuario];
            }
            
            
        }else{ //if (blnReturnCloud)
            
            NSLog(@"Error");
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"Error remoto al ingresar el cliente, intente nuevamente."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        
        
    }else{ //if ([self validarRegistro] == YES)
        blnRetorno = NO;
    }
    
    if (blnRetorno) {
        
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{

    bool blnRetorno = YES;
    
    if ([identifier isEqualToString:@"segueCheckOut"])
    {

    }
    
    if (blnRetorno) {
        
        return YES;
    }else{
        return NO;
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
 
    NSLog(@"Todo bien y validado");
    
}

- (IBAction)registerLogon:(id)sender {
    
    
    //Revisamos desde donde viene la solicitud de Login al sistema
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *myString = [prefs stringForKey:@"strCurrentTypeOfLogin"]; //1: Login normal, 2: Login desde el área personal
    
    bool blnRetorno = [self registerForm];
    
    if (blnRetorno) {
        
        if (([myString isEqualToString:@"1"])) {
            
            [self performSegueWithIdentifier:@"segueCheckOut" sender:nil];
            
        }else{
            
            [prefs setObject:@"1" forKey:@"strCurrentTypeOfLogin"]; //1: Login normal, 2: Login desde el área personal
            
            [self performSegueWithIdentifier:@"segueHomeArea" sender:nil];
        }
        
    }
    
    
    
}

@end












